package sealte.mynode.servlet.impl;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sealte.mynode.bean.UserBean;
import sealte.mynode.pojo.User;
import sealte.mynode.servlet.system.SystemPostServlet;
import sealte.mynode.util.Tools;

public class UserRegister extends SystemPostServlet {

	private static final long serialVersionUID = -4430357659932521504L;

	@Override
	protected void doBusinessService(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		PrintWriter out = resp.getWriter();
		
		String name = (String)req.getParameter("username");
		String pass = (String)req.getParameter("userpass");
		String email = (String)req.getParameter("email");
		
		User user = new User();
		user.setName(name);
		user.setPassword(pass);
		user.setEmail(email);
		user.setJoinTime(Tools.getCurrentDate());
		user.setOnline("Y");
		
		UserBean ub = new UserBean();
		boolean flag = ub.addNew(user);
		if(flag){
			user = ub.login(name, pass);
			req.getSession().setAttribute("user", user);
			resp.sendRedirect("home.jsp");
		}else{
			String path = req.getContextPath();
			String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"/";
			out.println("Register failed!");
			out.println("<a href=\""+basePath+"user_register.jsp\">Sign in again</a>");
		}
		
		if(null!=out){
			out.close();
		}
	}

}
